package main

import (
	"fmt"
	"sync"
)
//Web 爬虫
type Fetcher interface {
	//Fetch 返回 URL 的 body 内容，并且将在这个页面上找到的 URL 放到一个 slice 中。
	Fetch(url string) (body string, urls []string, err error)
}

var store map[string]bool
var wg sync.WaitGroup
// Crawl 使用 fetcher 从某个 URL 开始递归的爬取页面，直到达到最大深度。
func _crawl(url string, depth int, fetcher Fetcher, Results chan string, wg *sync.WaitGroup) {
	defer wg.Done()
	if depth <= 0 {
		return
	}
	if exists := store[url]; exists {
		return
	}
	body, urls, err := fetcher.Fetch(url)
	if err != nil {
		Results <- fmt.Sprintf("not found: %s", url)
		return
	}
	store[url] = true
	Results <- fmt.Sprintf("found: %s %q", url, body)
	for _, u := range urls {
		wg.Add(1)
		go _crawl(u, depth - 1, fetcher, Results, wg)
	}
}

func Crawl(url string, depth int, fetcher Fetcher) {
	Results := make(chan string)
	wg.Add(1)
	go _crawl(url, depth, fetcher, Results, &wg)
	go func() {
		wg.Wait()
		close(Results)
	}()
	for r := range Results {
		fmt.Println(r)
	}
}

func main() {
	store = make(map[string]bool)
	Crawl("http://golang.org/", 4, fetcher)
}

// fakeFetcher is Fetcher that returns canned results.
type fakeFetcher map[string]*fakeResult

type fakeResult struct {
	body string
	urls []string
}

func (f fakeFetcher) Fetch(url string) (string, []string, error) {
	if res, ok := f[url]; ok {
		return res.body, res.urls, nil
	}
	return "", nil, fmt.Errorf("not found: %s", url)
}

// fetcher is a populated fakeFetcher.
var fetcher = fakeFetcher{
	"http://golang.org/": &fakeResult{
		"The Go Programming Language",
		[]string{
			"http://golang.org/pkg/",
			"http://golang.org/cmd/",
		},
	},
	"http://golang.org/pkg/": &fakeResult{
		"Packages",
		[]string{
			"http://golang.org/",
			"http://golang.org/cmd/",
			"http://golang.org/pkg/fmt/",
			"http://golang.org/pkg/os/",
		},
	},
	"http://golang.org/pkg/fmt/": &fakeResult{
		"Package fmt",
		[]string{
			"http://golang.org/",
			"http://golang.org/pkg/",
		},
	},
	"http://golang.org/pkg/os/": &fakeResult{
		"Package os",
		[]string{
			"http://golang.org/",
			"http://golang.org/pkg/",
		},
	},
}
